package stewardapp

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/statistics"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
)

// GetHomeOperationData 首页运营数据
func GetHomeOperationData(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	var userIdArr []int
	var placeIdArr []int
	if userId != 2 {
		userIdArr = dao.NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placeIdArr = dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
	}

	// 入驻时间
	userInfo := dao.NewUserDao().GetUserInfoById(userId).Unwrap().(*users.UserModel)
	enterDay := (time.Now().Unix() - int64(userInfo.CreateAt)) / 60 / 60 / 24

	// 设备总条数
	deviceCount := dao.NewOrderDao().GetMattersCountDevice(placeIdArr, userId).Unwrap().(int64)

	placeNum := int64(len(placeIdArr))
	if userId == 2 {
		placeNum = dao.NewOrderDao().GetUserPlaceCount().Unwrap().(int64)
	}

	Response(c)("", CodeSuccess, &struct {
		DeviceCount int64 `json:"deviceCount"`
		EnterDay    int64 `json:"enterDay"`
		PlaceNum    int64 `json:"placeNum"`
		TeamNum     int64 `json:"teamNum"`
	}{
		DeviceCount: deviceCount,
		EnterDay:    enterDay,
		PlaceNum:    placeNum,
		TeamNum:     int64(len(userIdArr)),
	})(OK)
}

// GetOperationAnalysisDataAll 运营分析数据 总
func GetOperationAnalysisDataAll(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	result := request.GetOperationAnalysisDataRes{}
	var userIdArr, placeIdArr []int
	if userId != 2 {
		userIdArr = dao.NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placeIdArr = dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
	}

	// 交易总额、订单总数
	orderNumInfo := dao.NewOrderDao().GetUserTotalOrderAll(userId, "").Unwrap().(*request.TotalOrderAllRes)
	result.OrderAmount = orderNumInfo.Amount
	result.OrderCount = orderNumInfo.Num

	// 收益总额
	result.DividendAmount = dao.NewOrderDao().GetUserTotalDividendsAll(userId, "").Unwrap().(int64)

	// 独立用户数
	result.UserCount = dao.NewOrderDao().GetUserTotalOrderMembers(userId, "").Unwrap().(int64)

	// 提现总金额
	result.CashAmount = dao.NewOrderDao().GetCashLogByUserId(userId).Unwrap().(int64)

	// 设备总数
	result.DeviceCount = dao.NewOrderDao().GetMattersCountDevice(placeIdArr, userId).Unwrap().(int64)

	// 网点总数
	result.PlaceCount = int64(len(placeIdArr))
	if userId == 2 {
		result.PlaceCount = dao.NewOrderDao().GetUserPlaceCount().Unwrap().(int64)
	}

	Response(c)("", CodeSuccess, result)(OK)
}

// GetOperationAnalysisDataDay 运营分析数据 天
func GetOperationAnalysisDataDay(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	param := &request.GetOperationAnalysisDataDayRes{}
	dingo.ErrorIf(c.ShouldBindJSON(param)).Unwrap()

	result := request.GetOperationAnalysisDataDayReq{}
	//var userIdArr, placeIdArr []int
	//if userId != 2 {
	//	userIdArr = dao.NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	//	placeIdArr = dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
	//}

	// 交易总额、订单总数
	orderNumInfo := dao.NewOrderDao().GetUserTotalOrderAll(userId, param.InDay).Unwrap().(*request.TotalOrderAllRes)
	result.OrderAmount = orderNumInfo.Amount
	result.OrderCount = orderNumInfo.Num

	// 客单价
	if result.OrderAmount > 0 {
		result.AverageAmount = result.OrderAmount / result.OrderCount
	}

	// 收益总额
	result.DividendAmount = dao.NewOrderDao().GetUserTotalDividendsAll(userId, param.InDay).Unwrap().(int64)

	// 独立用户数
	//result.UserCount = dao.NewOrderDao().GetUserTotalOrderMembers(userId, param.InDay).Unwrap().(int64)

	// 设备/网点动销数
	activeInfo := dao.NewOrderDao().GetActiveCountPlaceDevice(userId, param.InDay).Unwrap().(*request.GetActiveCountPlaceDeviceReq)
	result.PlaceCount = activeInfo.PlaceNum
	result.DeviceCount = activeInfo.DeviceNum

	// 动销率
	// userIncome := dao.NewAgentCountDao().GetAgentIncomeInfo(userId, param.InDay)

	Response(c)("", CodeSuccess, result)(OK)
}

// GetTeamAnalysisList 团队排行
func GetTeamAnalysisList(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	isAdmin, err := helper.GetIsAdminFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	param := &request.GetAgentUserListByParentIdLimit{}
	dingo.ErrorIf(c.ShouldBindJSON(param)).Unwrap()
	param.UserId = userId

	data := dao.NewUserDao().GetTeamAnalysisList(param, isAdmin)
	userList := data.Unwrap().([]*request.GetAgentUserListByParentIdReq)
	for _, item := range userList {
		userIdArr := dao.NewUserDao().QueryChildUserIds(item.ID).Unwrap().([]int)
		placeIdArr := dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		item.TeamNum = len(userIdArr)
		item.PlaceNum = len(placeIdArr)

		if param.IsDividend {
			inMonth := time.Now().Format("2006-01")
			item.DividendMonthAmount = dao.NewOrderDao().GetUserTotalDividendsMonthAll(item.ID, inMonth).Unwrap().(int64)
		}
	}

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)

	//Response(c)("", CodeSuccess, userList)(OK)
}

// ----------------------------------- APP 经营分析 ---------------------------------------------------//

// 获取统计数据
func GetUserAnalysis(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	param := &struct {
		StatisticType string `form:"statisticType" json:"statisticType"` // 类型 all 总统计 day 天  month 月
		DateStr       string `form:"dateStr" json:"dateStr"`             // 天 2022-05-07 或 月 2022-05
		StartDate     string `form:"startDate" json:"startDate"`         // 开始日期
		EndDate       string `form:"endDate" json:"endDate"`             // 结束日期
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	data := &statistics.UserAnalysis{}
	data.UpdateTime = global.Rdb.Get(ctx, "statistics_update_time").Val()                                // 更新时间
	data.NowDate = time.Now().Format("2006-01-02") + " " + helper.GetWeek(time.Now().Weekday().String()) // 当前时间

	// 获取T-1 日统计分析
	t := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	analysisInfo := dao.NewStatisticsDao().GetUserStatisticsDataByDay(t, userId).Unwrap().(*statistics.UserAnalysisModel)

	if param.StatisticType == "day" { // 天数据
		if param.DateStr == "" { // 默认昨日
			data.UserAnalysisModel = analysisInfo
		} else {
			data.UserAnalysisModel = dao.NewStatisticsDao().GetUserStatisticsDataByDay(param.DateStr, userId).Unwrap().(*statistics.UserAnalysisModel)
		}
	} else if param.StatisticType == "month" { // 月数据 默认最近30天
		if param.StartDate == "" || param.EndDate == "" {
			param.StartDate = time.Now().AddDate(0, 0, -31).Format("2006-01-02")
			param.EndDate = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
		}
		data.UserAnalysisModel = dao.NewStatisticsDao().GetUserStatisticsDataByDayRange(param.StartDate, param.EndDate, userId).Unwrap().(*statistics.UserAnalysisModel)
	} else { // 默认总数据
		data.UserAnalysisModel = dao.NewStatisticsDao().GetUserStatisticsTotalDataByUserId(userId).Unwrap().(*statistics.UserAnalysisModel)
	}
	data.UserAnalysisModel.TotalPlace = analysisInfo.TotalPlace
	data.UserAnalysisModel.PlaceSales = analysisInfo.PlaceSales
	data.UserAnalysisModel.TotalDevices = analysisInfo.TotalDevices

	Response(ctx)("", CodeSuccess, data)(OK)
}

// 获取流水图表 - 折线图
func GetUserSettlementAnalysis(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	isAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	startDate := time.Now().AddDate(0, 0, -11).Format("2006-01-02")
	endDate := time.Now().AddDate(0, 0, -1).Format("2006-01-02") // 昨日

	lists := dao.NewStatisticsDao().GetUserStatisticsRangeDataByUserId(startDate, endDate, userId).Unwrap().([]*statistics.UserAnalysisModel)
	var categories []string
	var dtTotal, dtNoDraw, dtDraw []float64
	var series []*statistics.Series
	var seriesTotal, seriesNoDraw, seriesDraw *statistics.Series
	for _, lst := range lists {
		categories = append(categories, lst.DateStr[8:10])
		t, _ := decimal.NewFromFloat(lst.SettlementComplete).Round(2).Float64()
		dtTotal = append(dtTotal, t)
		noDraw, _ := decimal.NewFromFloat(lst.SettlementNormalTotal).Round(2).Float64()
		dtNoDraw = append(dtNoDraw, noDraw)
		draw, _ := decimal.NewFromFloat(lst.SettlementDraw).Round(2).Float64()
		dtDraw = append(dtDraw, draw)
	}
	seriesTotal = &statistics.Series{
		Name: "总流水",
		Data: dtTotal,
	}
	seriesNoDraw = &statistics.Series{
		Name: "订单流水",
		Data: dtNoDraw,
	}
	seriesDraw = &statistics.Series{
		Name: "奖励流水",
		Data: dtDraw,
	}
	if isAdmin == 10 {
		series = append(series, seriesTotal, seriesNoDraw, seriesDraw)
	} else {
		series = append(series, seriesNoDraw)
	}


	data := &statistics.UserStatisticData{}
	data.Categories = categories
	data.Series = series

	Response(ctx)("", CodeSuccess, data)(OK)
}

// 获取收益图表 - 折线图
func GetUserIncomeAnalysis(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	startDate := time.Now().AddDate(0, 0, -11).Format("2006-01-02")
	endDate := time.Now().AddDate(0, 0, -1).Format("2006-01-02") // 昨日

	lists := dao.NewStatisticsDao().GetUserStatisticsRangeDataByUserId(startDate, endDate, userId).Unwrap().([]*statistics.UserAnalysisModel)
	var categories []string
	var dtTotal []float64
	var series []*statistics.Series
	var seriesTotal *statistics.Series
	for _, lst := range lists {
		//categories = append(categories, lst.DateStr)
		categories = append(categories, lst.DateStr[8:10])
		p, _ := decimal.NewFromFloat(lst.TotalIncome).Round(2).Float64()
		dtTotal = append(dtTotal, p)
	}
	seriesTotal = &statistics.Series{
		Name: "收益",
		Data: dtTotal,
	}
	series = append(series, seriesTotal)
	data := &statistics.UserStatisticData{}
	data.Categories = categories
	data.Series = series

	Response(ctx)("", CodeSuccess, data)(OK)
}

// 获取订单笔数 - 混合图
func GetUserOrderTotalAnalysis(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	startDate := time.Now().AddDate(0, 0, -11).Format("2006-01-02")
	endDate := time.Now().AddDate(0, 0, -1).Format("2006-01-02") // 昨日

	lists := dao.NewStatisticsDao().GetUserStatisticsRangeDataByUserId(startDate, endDate, userId).Unwrap().([]*statistics.UserAnalysisModel)
	var categories []string
	var dtTotal []float64
	var dtPrice []float64
	var series []*statistics.Series
	var seriesTotal, seriesPrice *statistics.Series
	for _, lst := range lists {
		//categories = append(categories, lst.DateStr)
		categories = append(categories, lst.DateStr[8:10])
		t, _ := decimal.NewFromInt(lst.TotalComplete).Round(0).Float64()
		dtTotal = append(dtTotal, t)
		var price float64
		if lst.TotalComplete > 0 {
			price, _ = decimal.NewFromFloat(lst.SettlementComplete).Div(decimal.NewFromInt(lst.TotalComplete)).Round(2).Float64()
		} else {
			price = 0
		}
		dtPrice = append(dtPrice, price)
	}
	// 柱
	seriesTotal = &statistics.Series{
		Name: "订单笔数",
		Type: "column",
		Data: dtTotal,
	}
	// 折线
	seriesPrice = &statistics.Series{
		Name:  "单价",
		Type:  "line",
		Data:  dtPrice,
		Index: 1,
	}
	series = append(series, seriesTotal, seriesPrice)
	data := &statistics.UserStatisticData{}
	data.Categories = categories
	data.Series = series

	Response(ctx)("", CodeSuccess, data)(OK)
}

// 获取门店动销 - 混合图
func GetUserPlaceSaleAnalysis(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	startDate := time.Now().AddDate(0, 0, -11).Format("2006-01-02")
	endDate := time.Now().AddDate(0, 0, -1).Format("2006-01-02") // 昨日

	lists := dao.NewStatisticsDao().GetUserStatisticsRangeDataByUserId(startDate, endDate, userId).Unwrap().([]*statistics.UserAnalysisModel)
	var categories []string
	var dtTotal, dtPlaceSales, dtSaleRate []float64
	var series []*statistics.Series
	var seriesTotal, seriesPrice, saleRate *statistics.Series
	for _, lst := range lists {
		//categories = append(categories, lst.DateStr)
		categories = append(categories, lst.DateStr[8:10])
		t, _ := decimal.NewFromInt(lst.TotalPlace).Round(0).Float64() // 门店总数
		dtTotal = append(dtTotal, t)
		var price float64
		if lst.PlaceSales > 0 {
			price, _ = decimal.NewFromInt(lst.PlaceSales).Round(0).Float64() // 门店动销数
		} else {
			price = 0
		}
		dtPlaceSales = append(dtPlaceSales, price)
		rate, _ := decimal.NewFromInt(lst.PlaceSales).Div(decimal.NewFromInt(lst.TotalPlace)).Round(2).Float64()
		dtSaleRate = append(dtSaleRate, rate)
	}
	// 门店总数
	seriesTotal = &statistics.Series{
		Name:  "门店总数",
		Index: 1,
		Type:  "column",
		Data:  dtTotal,
	}
	// 动销数
	seriesPrice = &statistics.Series{
		Name:  "动销数",
		Index: 1,
		Type:  "column",
		Data:  dtPlaceSales,
	}
	// 动销率
	saleRate = &statistics.Series{
		Name:  "动销率",
		Type:  "line",
		Index: 0,
		Data:  dtSaleRate,
	}
	series = append(series, seriesTotal, seriesPrice, saleRate)
	data := &statistics.UserStatisticData{}
	data.Categories = categories
	data.Series = series

	Response(ctx)("", CodeSuccess, data)(OK)
}

// 获取统计列表 - 分页
func GetUserAnalysisList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.AnalysisUserReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	var data *dingo.ErrorWrap
	if param.StatisticType == "month" {
		data = dao.NewStatisticsDao().GetUserStatisticsMonthDataByUserId(param, userId) // 按月
	} else {
		data = dao.NewStatisticsDao().GetUserStatisticsDayDataByUserId(param, userId) // 按日
	}
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}
